using System;
using Mbs.Modularity.AddIns;

namespace Mbs
{
    public static class MVPExtensions
    {

        public static T BuildItem<T>(this IView view, string addInItemPath)
        {
            return (T)BuildItem(view,addInItemPath);
        }

        public static object BuildItem(this IView view, string addInItemPath)
        {
            return InternalBuildItem(view, addInItemPath);
        }

        public static T BuildItem<T>(this IPresenter presenter, string addInItemPath)
        {
            return (T)BuildItem(presenter, addInItemPath);
        }

        public static object BuildItem(this IPresenter presenter, string addInItemPath)
        {
            return InternalBuildItem(presenter, addInItemPath);
        }

        private static object InternalBuildItem(object obj, string addInItemPath)
        {
            var addInTree = ServiceLocator.Current.Get<IAddInTree>();
            var node = addInTree.Get(addInItemPath.Trim());
            if (node == null)
                return null;

            try
            {
                return node.Build(obj);
            }
            catch (Exception ex)
            {
                var newEx = new Exception("Build Path[" + addInItemPath + "] in AddIn[" + node.AddInName + "] exception. " + ex.Message, ex);
                newEx.RaiseException();
            }
            return null;
        }


      
    }
}
